<?
/*******************************************************************************
Copyright (c) 2007, Chris Heald. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this 
list of conditions and the following disclaimer. 

* Redistributions in binary form must reproduce the above copyright notice, this 
list of conditions and the following disclaimer in the documentation and/or 
other materials provided with the distribution. 

* Neither the name of the Author nor the names of its contributors may be used 
to endorse or promote products derived from this software without specific prior 
written permission.

* You are free to use this software in any commercial or non-commercial capacity 
you wish, provided that the following conditions are met:

	1) The original author and any contributors are given visible credit for the 
	tool on each page of the tool and on pages generated by the tool. If your tool 
	does not generate visible pages, then simply place a comment with appropriate
	credit in your code.

	2) You make a good-faith effort to contribute modifications, contributions, and 
	changes to this tool back to the community by releasing them under a license 
	similar to this one. This is non-binding, but is greatly appreciated. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/

session_start();
include("_armory.php");
$xmlDataCache = array();
ini_set("user_agent", "Mozilla/5.0 Gecko/20070219 Firefox/2.0.0.2");

$factions = array();
$classes = array();
$charsData = array();

function getGuildReputations($base_url, $realm, $guild, $minLevel) {
	global $factions, $classes, $charsData;
	$guildMembers = getGuildMembers($base_url, $realm, $guild, $minLevel);
	$repList = array();
		$c = 0;
	foreach($guildMembers as $guildMember) {
		$charData = getCharacterData($base_url, $realm, $guildMember[0]);

		
		$charInfo = $charData->xpath("/page/characterInfo/character");
		$attribs = attribs($charInfo[0]);
		
		$spec = "";
		try {
			$charSpec = $charData->xpath("/page/characterInfo/characterTab/talentSpec");
			$specAttribs = attribs($charSpec[0]);
			
			$spec = $specAttribs["treeOne"] . "/" . $specAttribs["treeTwo"] . "/" . $specAttribs["treeThree"];
		} catch(Exception $e) {
			$spec = "0/0/0";
		}
		
		$charsData[$attribs["name"]] = array(
			"class"		=>	$attribs["class"],
			"level"		=>	$attribs["level"],
			"realm"		=>	$realm,
			"spec"		=>	$spec,
		);
		
		
		$factionCategories = $charData->xpath("/page/characterInfo/reputationTab/factionCategory");
		foreach($factionCategories as $factionCategory) {
			$attribs = attribs($factionCategory);
			$single_keys = array("thevioleteye", "keepersoftime", "thesha'tar", "lowercity", "honorhold", "thrallmar", "cenarionexpedition");

			foreach($factionCategory->faction as $faction) {
				$attribs = attribs($faction);
				if (in_array($attribs["key"], $single_keys)) {
					if(!$repList[$guildMember[0]])
						$repList[$guildMember[0]] = array();
					$factions[$attribs["name"]] = 1;
					$hasKey = false;
					if($attribs["reputation"] > 21000)
						$hasKey = true;
					if($attribs["reputation"] >= 1850 && $attribs["key"] == "thevioleteye")
						$hasKey = true;
					$repList[$guildMember[0]][$attribs["name"]] = $hasKey;
					$classes[$guildMember[0]] = $guildMember[2];
				}
			}
		}

		// if($c++ == 15) break;
	}
	ksort($repList);
	return $repList;
}

function writeReputations($reps, $realm, $guild, $title, $minLevel) {
	global $factions, $classes, $charsData, $base_url;
	$filename = strtolower(preg_replace("/[^a-zA-Z0-9]/", "-", $realm) . "-" . preg_replace("/[^a-zA-Z']/", "-", $guild)) . "-$minLevel.html";
	$file = fopen("heroics_out/$filename", "w");
	fwrite($file, "
			<html>
				<head>
					<title>$guild summary</title>
					<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>
					
					<script src='../static/sorttable.js'></script>
					<script src='../static/prototype.js'></script>
					<script src='../static/tooltip.js'></script>
					<link rel='stylesheet' type='text/css' href='../static/comparison.css' />
					<link rel='stylesheet' type='text/css' href='../static/heroics.css' />
				</head>
				<body>
	");
	fwrite($file, "<h1>$title Key Listing</h1><h3>Last Updated: " . strftime("%Y/%m/%d %T %z") . "</h3>\n");
	fwrite($file, "<table border='1' default_sort='0'>\n");
	fwrite($file, "<tr class='sorthead'><th>Character</th>");
	fwrite($file, "<th>Class</th><th>Spec</th>");
	$factions = array_keys($factions);
	sort($factions);
	foreach($factions as $faction) {
		fwrite($file, "<th>$faction</th>");
	}
	fwrite($file, "</tr>\n");
	
	foreach($reps as $char => $rep) {
		fwrite($file, "<tr><td class='c'><a href=\"$base_url/character-sheet.xml?r=" . urlencode(stripslashes($charsData[$char]["realm"])) . "&n=" . urlencode(stripslashes($char)) . "\">$char</a></td>");
		fwrite($file, "<td value='" . $charsData[$char]["class"] . "-" . $charsData[$char]["level"] . "'class='" . $charsData[$char]["class"] . "'>" . $charsData[$char]["level"] . " " . $charsData[$char]["class"] . "</td>");
		fwrite($file, "<td>" . $charsData[$char]["spec"] . "</td>");
		foreach($factions as $faction) {
			if($rep[$faction]) {
				$mark = "<img src='../static/images/checkmark.gif'>";
			} else {
				$mark = "";
			}
			fwrite($file, "<td class='fc'>$mark</td> ");
		}
		fwrite($file, "</tr>\n");
	}
	fwrite($file, "</table>");
	
	fwrite($file, "<!-- please leave this credit notice intact. I worked very hard on these tools. :) //-->");
	fwrite($file, "<p />Generated by Antiarc's Guild Summary tools at <a href='http://wow.tachyonsix.com/armory/'>http://wow.tachyonsix.com/armory</a>.\n");
	fwrite($file, "</body></html>");
	fclose($file);
	return $filename;
}

?>

<link rel="stylesheet" type="text/css" href="style.css" />
<div class="container">

<? include("ads/_vert_ads.php"); ?>

<?

if(@$_REQUEST["realm"] && @$_REQUEST["guild"] && (@$_REQUEST["gen_id"] == @$_SESSION["gen_id"] || true)) {
	$_SESSION["gen_id"] = false;
	$base_url = "http://armory.worldofwarcraft.com";
	if(@$_REQUEST["loc"] == "EU")
		$base_url = "http://armory.wow-europe.com";
		
	$guilds = explode(",", $_REQUEST["guild"]);
	$reps = array();
	$minLevel = (int)@$_REQUEST["minlevel"];
	if(!$minLevel) $minLevel = 68;
	try {
		foreach($guilds as $guild) {
			if(@$_REQUEST["notrim"])
				$reps = array_merge_recursive($reps, getGuildReputations($base_url, @$_REQUEST["realm"], $guild, $minLevel));
			else
				$reps = array_merge_recursive($reps, getGuildReputations($base_url, @$_REQUEST["realm"], trim($guild), $minLevel));
		}
		$title = @$_REQUEST["guild"];
		if(@$_REQUEST["title"])
			$title = $_REQUEST["title"];
		$filename = writeReputations($reps, @$_REQUEST["realm"], @$_REQUEST["guild"], $title, $minLevel);
		echo "<h3>Summary complete. Please see results at <a href=\"heroics_out/$filename\">$filename</a>. Please link to the HTML file rather than this script when sharing the results.</h3>";
	} catch (Exception $e) {
		echo "<font style='font-weight: bold; color: #f00;'>ERROR: " . $e->getMessage() . "</font><p />";
	}
}
$_SESSION["gen_id"] = rand(1, 100000);
?>
<h3>Guild heroic keying overview generator</h3>
Enter the information below to request an up-to-date guild summary from the Armory. Data is cached for 12 hours, so you won't get different results if you run it more often than that.
<p/>
For an example of the output, see <a href="heroics_out/cenarion-circle-southsea-buccaneers-60.html">this page</a>.
<p />
If you want to <a href="heroics_out/">browse already-generated summaries</a>, you can do so as well. You might try looking here for your file if your browser seems to stall and never come back.
<p />
<form method="get">
	<table>
  		<tr><td align="right">Realm (exact):</td><td><input type="text" name="realm"></td></tr>
		<tr><td align="right">Guild name (exact):</td><td><input type="text" name="guild"></td></tr>
		<tr><td align="right">Guild name (to display,<br />blank to use provided):</td><td><input type="text" name="title"></td></tr>
		<tr><td align="right">Minimum level:</td><td><input type="text" name="minlevel" value="68"></td></tr>
	</table>
	<input type="radio" checked name="loc" value="US"> US
	<input type="radio" name="loc" value="EU"> EU<p />
	<input type="checkbox" name="notrim"> Don't trim guild names (you only need this if your guild starts/ends with a space)
	<input type="hidden" name="gen_id" value="<?=$_SESSION["gen_id"] ?>">
	<p />
	
	<input type="submit" />
	<p />
	Please be patient. This pulls a lot of data from the WoW Armory and takes a bit to complete.
	<p />
	If you want to compare multiple guilds, enter them in a comma-delimited format.
	<p />
	Example: Southsea Buccaneers, Unbroken
</form>
<? include("_footer.php"); ?>

</div>
<?
logReferer("HeroicsList");
?>